<template>
  <view class="GoodsList">
    <view class="GoodsList-header">
      <u-search
        v-model="listQuery.name"
        shape="square"
        :show-action="true"
        actionText="搜索"
        :animation="false"
        disabled
      />
    </view>
     <view class="GoodsList-menu flex fs14">
       <text :class="[listQuery.orderType === '' ? 'activeColor' : '']" @click="setOrderType('')">综合</text>
       <view class="flex"  @click="setOrderType('salesDESC')">
         <text :class="[listQuery.orderType === 'sales' || listQuery.orderType === 'salesDESC' ? 'activeColor' : '']">销量</text>
         <view class="flexCol ml5">
           <u-icon name="arrow-up-fill" size="12rpx" :color="listQuery.orderType === 'sales' ? '#ea64a2' : '#606266'"></u-icon>
           <u-gap height="3" />
           <u-icon name="arrow-down-fill" size="12rpx" :color="listQuery.orderType === 'salesDESC' ? '#ea64a2' : '#606266'"></u-icon>
         </view>
        </view>
       <view class="flex"  @click="setOrderType('priceDESC')">
         <text :class="[listQuery.orderType === 'price' || listQuery.orderType === 'priceDESC' ? 'activeColor' : '']">价格</text>
         <view class="flexCol ml5">
           <u-icon name="arrow-up-fill" size="12rpx" :color="listQuery.orderType === 'price' ? '#ea64a2' : '#606266'"></u-icon>
           <u-gap height="3" />
           <u-icon name="arrow-down-fill" size="12rpx" :color="listQuery.orderType === 'priceDESC' ? '#ea64a2' : '#606266'"></u-icon>
         </view>
       </view>
       <view class="flex" @click="openPicker">
         <text>筛选</text>
         <u-icon name="list"></u-icon>
       </view>
     </view>
    <view class="GoodsList-list">
      <u-skeleton
	      rows="6"
	    	:loading="loading"
	    	:title="false"
        rowsHeight="150"
	    >
      <view v-if="tableData.length > 0" class="GoodsList-list-list flexWrap">
        <view v-for="(item, index) in tableData" :key="index" class="GoodsList-list-list-item">
          <Cgoodscard :goods="item" />
        </view>
      </view>
	  <u-loadmore v-if="tableData.length > 0" :status="indexStatus" loadmoreText="点击加载更多" loadingText="努力加载中" nomoreText="实在没有了" />
	  <u-empty v-else text="暂无数据哦~" class="mt30" />
      </u-skeleton>
    </view>
    <u-picker
      :show="picker.show"
      ref="uPicker"
      :loading="picker.loading"
      :columns="picker.columns"
      keyName="name"
      closeOnClickOverlay
      @close="closePickerHandler"
      @cancel="closePickerHandler"
      @change="changePickerHandler"
      @confirm="confirmPickerHandler"
    />
  </view>
</template>

<script>
export default {
  name: "GoodsList", // 商品搜索筛选 列表展示
  options: { styleIsolation: "shared" }, // 父组件设置 options.styleIsolation 可穿透子组件，以及页面
  data() {
    return {
      loading: true, // 页面骨架屏
      indexStatus: 'loadmore', // 下拉加载状态
      tableData: [], // 商品主数据
      listQuery: { // 页面
        page: 1,
        size: 6,
        total: 0,
        pageNum: 0,
        orderType: '', // orderType 排序类别('' 综合排序，salesDESC销量降序， sales销量升序，price价格升序，priceDESC价格降序)
        name: "", // 搜索值
        categoryTwoId: '' // 分类Id
      },
      picker: { // 选择器
        loading: false,
        show: false,
        columns: [], // 设置每一列的数据
        sonColumns: [], // 第二级子数据
      }
    };
  },
  onShow() {
    const routes = getCurrentPages();
    this.listQuery.name = routes[routes.length - 1]?.options?.name || '';
    this.listQuery.categoryTwoId = routes[routes.length - 1]?.options?.categoryTwoId || '' 
    this.loading = true // 页面骨架屏
    this.indexStatus = 'loadmore', // 下拉加载状态
    this.tableData = [], // 商品主数据
    this.listQuery.page = 1
    this.listQuery.size = 6
    this.listQuery.pageNum = 0
    this.getList()
  },
  // 页面滚动到底部的事件（不是scroll-view滚到底），常用于下拉下一页数据
	onReachBottom() {
		if (this.listQuery.page === this.listQuery.pageNum) { // 已到最后一页
			this.indexStatus = 'nomore'
			return
		}
		this.indexStatus = 'loading ' // 开始加载
		this.listQuery.page = this.listQuery.page + 1
		this.getList()
	},
  methods: {
    // 初始化列表
    async getList() {
      this.loading = true
      const { code, data } = await this.$goods.goodsGetGoodsList(this.listQuery)
      if (code === 0) {
        this.tableData.push(...data.list)
        this.listQuery.total = data.total
        this.listQuery.pageNum = data.pageNum
        this.picker.show = false
        this.indexStatus = this.listQuery.page === this.listQuery.pageNum ? 'nomore' : 'loadmore' // 下拉加载判断
        setTimeout(() => { this.loading = false }, 400)
      }
    },
    // 选择器确认回调
    confirmPickerHandler({ indexs }) {
      // indexs 选择的ids数组
      const index = indexs[indexs.length - 1] // 获取最后一个id的索引
      const categoryTwoId = this.picker.columns[indexs.length-1][index].id // 获取组件数据第二列的值
      this.listQuery.categoryTwoId = categoryTwoId
      this.loading = true // 页面骨架屏
      this.indexStatus = 'loadmore', // 下拉加载状态
      this.tableData = [], // 商品主数据
      this.listQuery.page = 1
      this.listQuery.size = 6
      this.listQuery.pageNum = 0
      this.getList()
    },
    // 关闭选择器
    closePickerHandler() {
      this.picker.show = false
    },
    // 选择器选择值发生变化后触发
    async changePickerHandler(e) {
      const {
        columnIndex, // 第几列索引
        index, // 当前列数据索引
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				picker = this.$refs.uPicker
      } = e
      console.log(columnIndex, index, picker)
      if (columnIndex === 0) { // 改变第一列的值
        if (!this.picker.sonColumns[index]) { // 对应子数据为空
          this.picker.loading = true
          const { code, data } = await this.$category.goodsCategoryTwo({ id: this.picker.columns[columnIndex][index].id })
          if (code === 0) {
            this.picker.sonColumns[index] = data
            this.picker.columns[1] = this.picker.sonColumns[index] // 本地数据
            picker.setColumnValues(1, this.picker.sonColumns[index]) // 组件数据
            this.picker.loading = false
          }
        } else { // 已存在数据
          picker.setColumnValues(1, this.picker.sonColumns[index])
        }
      }
    },
    // 打开选择器
    async openPicker() {
      this.picker.loading = true
	  this.picker.columns = []
      const { code, data } = await this.$category.goodsCategoryOne()
      if (code === 0) {
        this.picker.columns.push(data)
        this.picker.show = true
        this.picker.loading = false
        if (data.length > 0) { // 初始给第一列第一项添加子数据
          const { code, data } = await this.$category.goodsCategoryTwo({ id: this.picker.columns[0][0].id })
          if (code === 0) {
            this.picker.sonColumns[0] = data
            this.picker.columns[1] = this.picker.sonColumns[0] // 本地数据
            this.$refs.uPicker && this.$refs.uPicker.setColumnValues(1, this.picker.sonColumns[0]) // 组件数据
          }
        }
      }
    },
    // 设置列表排序
    setOrderType(type) {
      // 默认点击降序（再次点击升序）
      if (this.listQuery.orderType === type) { // 设置为升序（数值相同为再次点击）
        this.listQuery.orderType = type.substring(0, type.length - 4) // 去掉后4位DESC
      } else {
        this.listQuery.orderType = type
      }
      this.loading = true // 页面骨架屏
      this.indexStatus = 'loadmore', // 下拉加载状态
      this.tableData = [], // 商品主数据
      this.listQuery.page = 1
      this.listQuery.size = 6
      this.listQuery.pageNum = 0
      this.getList()
    }
  },
};
</script>

<style lang="scss" scoped>
.activeColor{
  color: $uni-color-primary
}

// 骨架屏占位100%
/deep/ .u-skeleton__wrapper__content{
  display: flex;
  align-items: center;
  flex-direction: row !important;
  flex-wrap: wrap;
  width: 100%;
  box-sizing: border-box;
  padding: 10rpx;
  &__rows{
    flex: 0 0 48%;
    margin-right: 20rpx;
    margin-top: 10rpx !important;
  }
  &__rows:nth-child(even){
    margin-right: 0 !important;
  }
}

.GoodsList{
  color: #606266;
  &-header{
    background: #ffffff;
    padding: 15rpx 20rpx;
  }
  &-menu{
    background: #ffffff;
    padding: 20rpx 30rpx;
    justify-content: space-between;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  }
  // 弹出层
  &-popup{
    padding: 20rpx;
  }
  &-list{
    &-list {
				&-item {
					box-sizing: border-box;
					flex: 0 0 50%;
					padding: 10rpx;
				}
			}
  }
}
</style>
